package com.wsx.ones.boots.api;

import com.wsx.ones.boots.bean.Message;
import com.wsx.ones.boots.service.FutureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by wangshuaixin on 18/6/15.
 */
@RestController
public class DeferApi {


    private static final long TIMEOUT = 1000L;

    private AtomicLong id = new AtomicLong(0);

    @Autowired
    private FutureService futureService;

    @RequestMapping(
            value = "/hello",
            method = {RequestMethod.GET}
    )
    public String hello() {
        return "hello world";
    }


    @RequestMapping(
            value = "/async",
            method = {RequestMethod.GET}
    )
    public DeferredResult<Message> getAsyncNonBlocking() {
        final DeferredResult<Message> result = new DeferredResult<Message>(TIMEOUT);
        CompletableFuture<Message> future = futureService.get("async-non-blocking", id.incrementAndGet());
        future.whenComplete((r,e) -> {
            if (e != null) {
                result.setErrorResult(e);
            } else {
                result.setResult(r);
            }
        });
        return result;
    }

}
